export class Controller{
    constructor(controllerId){
        this.controllerId = controllerId
        this.buttonStatusArray = new Array(24)
        for(let i=0;i<this.buttonStatusArray.length;i++){
            this.buttonStatusArray[i] = 0
        }
        this.buttonRightIndex = 7
        this.buttonLeftIndex = 6
        this.buttonDownIndex = 5
        this.buttonUpIndex = 4
        this.buttonStartIndex = 3
        this.buttonSelectIndex = 2
        this.buttonBIndex = 1
        this.buttonAIndex = 0
        this.readButtonIndex = 0
    }

    // 写4016端口时调用
    resetIndex(){
        this.readButtonIndex = 0
    }

    // 读4016和4017端口时用
    readCurrentButton(){
        // console.log('reading button:'+this.readButtonIndex)
        let status = this.buttonStatusArray[this.readButtonIndex]
        // console.log('status:'+status)
        this.readButtonIndex++
        if(this.readButtonIndex >= 24){
            this.readButtonIndex = 0
        }
        return status;
    }

    setButtonStatus(buttonName,action){
        // console.log('buttonName:'+buttonName+';  action:'+action)
        let buttonStatus
        if(action == 'press'){
            buttonStatus = 1
        }
        else if(action == 'release'){
            buttonStatus = 0
        }
        switch(buttonName){
            case 'left':
                this.buttonStatusArray[this.buttonLeftIndex] = buttonStatus
                // console.log('controller:'+this.buttonStatusArray)
                break
            case 'right':
                this.buttonStatusArray[this.buttonRightIndex] = buttonStatus
                // console.log('controller:'+this.buttonStatusArray)
                break
            case 'up':
                this.buttonStatusArray[this.buttonUpIndex] = buttonStatus
                // console.log('controller:'+this.buttonStatusArray)
                break
            case 'down':
                this.buttonStatusArray[this.buttonDownIndex] = buttonStatus
                // console.log('controller:'+this.buttonStatusArray)
                break
            case 'select':
                this.buttonStatusArray[this.buttonSelectIndex] = buttonStatus
                // console.log('controller:'+this.buttonStatusArray)
                break
            case 'start':
                this.buttonStatusArray[this.buttonStartIndex] = buttonStatus
                // console.log('controller:'+this.buttonStatusArray)
                break
            case 'b':
                this.buttonStatusArray[this.buttonBIndex] = buttonStatus
                // console.log('controller:'+this.buttonStatusArray)
                break
            case 'a':
                this.buttonStatusArray[this.buttonAIndex] = buttonStatus
                // console.log('controller:'+this.buttonStatusArray)
                break
        }
    }
}